package com.kristin.thread;

public class ObjectLockTest {

    static class A implements Runnable {

        private String name;

        private Object a;

        public A(String name, Object a) {
            this.name = name;
            this.a = a;
        }


        @Override
        public void run() {
            System.out.println("run方法内：" + Thread.currentThread().getName() + "状态为" + Thread.currentThread().getState());
            synchronized (a) {
                try {
                    a.wait();
                    // 竞争到该对象锁
                    System.out.println("竞争到锁执行" + name);
                    Thread.sleep(2000);
                    System.out.println("休眠完成" + name);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object lock = new Object();
        Thread thread1 = new Thread(new A("任务一" , lock));
        System.out.println(thread1.getName() + "状态为" + thread1.getState());
        thread1.start();
        Thread thread2 = new Thread(new A("任务二" , lock));
        System.out.println(thread2.getName() + "状态为" + thread2.getState());
        thread2.start();
        // 2秒之后，唤醒其中的一条线程
        Thread.sleep(2000);
        synchronized (lock) {
            System.out.println("lock代码块内的thread1的线程状态是" + thread1.getState());
            lock.notifyAll();
        }

        Thread.sleep(5000);
        System.out.println("执行完成thread1的线程状态是" + thread1.getState());
    }

}
